package yt.spider.view;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.grantland.widget.AutofitTextView;
import yt.spider.R;
import yt.spider.help.ReadBookControl;

public class BookContentView extends FrameLayout {
    public long qTag = System.currentTimeMillis();

    public static final int DurPageIndexBegin = -1;
    public static final int DurPageIndexEnd = -2;

    @BindView(R.id.iv_bg)
    ImageView ivBg;
    @BindView(R.id.tv_title)
    AutofitTextView tvTitle;
    @BindView(R.id.tv_page)
    TextView tvPage;
    @BindView(R.id.v_bottom)
    View vBottom;
    @BindView(R.id.tv_content)
    ContentTextView tvContent;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.tv_loading)
    TextView tvLoading;
    @BindView(R.id.tv_error_info)
    TextView tvErrorInfo;
    @BindView(R.id.tv_load_again)
    TextView tvLoadAgain;
    @BindView(R.id.ll_error)
    LinearLayout llError;

    private SharedPreferences preferences;

    private String title;
    private String content;
    private int durChapterIndex;
    private int chapterAll;
    private int durPageIndex;      //如果durPageIndex = -1 则是从头开始  -2则是从尾开始
    private int pageAll;

    //加载数据监听者
    private ContentSwitchView.LoadDataListener loadDataListener;

    //建立数据监听者
    private SetDataListener setDataListener;

    //抽象建立数据监听者
    public interface SetDataListener {
        //建立数据完成,需要实现方法
        // 需要传入的变量:书籍内容view,当前章节索引,章节总数,当前页数索引,总页数,来自页数索引
        void setDataFinish(BookContentView bookContentView, int durChapterIndex,
                           int chapterAll, int durPageIndex, int pageAll, int fromPageIndex);
    }

    public BookContentView(Context context) {
        this(context, null);
    }

    public BookContentView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BookContentView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public BookContentView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    //刷新数据
    public void init() {
        View view;
        if (preferences.getBoolean("hide_status_bar", false)) {
            view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_content_hide_status_bar, this, false);
        } else {
            view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_content_show_status_bar, this, false);
        }
        addView(view);
        ButterKnife.bind(this, view);

        tvLoadAgain.setOnClickListener(v -> {
            if (loadDataListener != null)
                loading();
        });
    }

    public void showLoading() {
        //加载界面,三层控件显示情况
        llError.setVisibility(GONE);  //隐藏
        tvLoading.setVisibility(VISIBLE); //显示
        llContent.setVisibility(INVISIBLE);  //阅读界面隐藏,控件依旧占用空间
    }

    public void loading() {
        llError.setVisibility(GONE);
        tvLoading.setVisibility(VISIBLE);
        llContent.setVisibility(INVISIBLE);
        qTag = System.currentTimeMillis();
        //执行请求操作
        if (loadDataListener != null) {
            loadDataListener.loadData(this, qTag, durChapterIndex, durPageIndex);
        }
    }

    public void finishLoading() {
        //完成加载时,三层界面显示情况
        llError.setVisibility(GONE); //控件彻底隐藏,不占用空间
        llContent.setVisibility(VISIBLE);  //显示阅读界面
        tvLoading.setVisibility(GONE);  //控件彻底隐藏,不占用空间
    }

    @SuppressLint("DefaultLocale")
    public void setNoData(String contentLines) {
        this.content = contentLines;
        tvPage.setText(String.format("%d/%d", this.durPageIndex + 1, this.pageAll));
        finishLoading();
    }

    //更新数据,更新标签,标题,内容行数,章节列表索引值,所有章节目录,当前章节索引值,当前章节页面索引
    public void updateData(long tag, String title, List<String> contentLines,
                           int durChapterIndex, int chapterAll, int durPageIndex, int durPageAll) {
        if (tag == qTag) {

            if (contentLines == null) {
                this.content = "";
            } else {
                StringBuilder s = new StringBuilder();
                for (int i = 0; i < contentLines.size(); i++) {
                    //一页页读出页面内容,写入字符串变量(非线程安全)s
                    s.append(contentLines.get(i));
                }
                //写入string内容变量content
                this.content = s.toString();
            }
            //传递写入信息
            this.title = title;
            this.durChapterIndex = durChapterIndex;
            this.chapterAll = chapterAll;
            this.durPageIndex = durPageIndex;
            this.pageAll = durPageAll;

            //写入标题
            tvTitle.setText(this.title);
            //写入小说文本内容
            tvContent.setText(this.content);
            //建立 "当前页数/总页数"  text文本显示
            tvPage.setText(String.format("%d/%d", this.durPageIndex + 1, this.pageAll));

            if (setDataListener != null) {
                setDataListener.setDataFinish(this, durChapterIndex, chapterAll, durPageIndex, durPageAll, this.durPageIndex);
            }
            //完成加载
            finishLoading();
        }
    }

    public void loadData(String title, int durChapterIndex, int chapterAll, int durPageIndex) {
        //加载时,页面需要显示的各项数据,页面文字赋值空
        this.title = title;
        this.durChapterIndex = durChapterIndex;
        this.chapterAll = chapterAll;
        this.durPageIndex = durPageIndex;
        tvTitle.setText(title);
        tvPage.setText("");

        loading();

    }

    public ContentSwitchView.LoadDataListener getLoadDataListener() {
        return loadDataListener;
    }

    public void setLoadDataListener(ContentSwitchView.LoadDataListener loadDataListener,
                                    SetDataListener setDataListener) {
        this.loadDataListener = loadDataListener;
        this.setDataListener = setDataListener;
    }

    public void setLoadDataListener(ContentSwitchView.LoadDataListener loadDataListener) {
        this.loadDataListener = loadDataListener;
    }

    public void loadError() {
        //加载错误时,三种组件显示情况
        llError.setVisibility(VISIBLE); //显示
        tvLoading.setVisibility(GONE);  //隐藏
        llContent.setVisibility(INVISIBLE); //隐藏
    }

    //创建一系列可get或set到相关信息的函数

    //得到page文本全部
    public int getPageAll() {
        return pageAll;
    }

    public void setPageAll(int pageAll) {
        this.pageAll = pageAll;
    }

    //得到当前页索引
    public int getDurPageIndex() {
        return durPageIndex;
    }

    public void setDurPageIndex(int durPageIndex) {
        this.durPageIndex = durPageIndex;
    }

    //得到当前章节索引
    public int getDurChapterIndex() {
        return durChapterIndex;
    }

    public void setDurChapterIndex(int durChapterIndex) {
        this.durChapterIndex = durChapterIndex;
    }

    //得到所有章节数
    public int getChapterAll() {
        return chapterAll;
    }

    public void setChapterAll(int chapterAll) {
        this.chapterAll = chapterAll;
    }

    //得到建立数据监听者
    public SetDataListener getSetDataListener() {
        return setDataListener;
    }

    public void setSetDataListener(SetDataListener setDataListener) {
        this.setDataListener = setDataListener;
    }

    //得到Q标签
    public long getQTag() {
        return qTag;
    }

    public void setQTag(long qTag) {
        this.qTag = qTag;
    }

    //得到tvcontent内容(显示文本的text)
    public TextView getTvContent() {
        return tvContent;
    }

    //得到内容
    public String getContent() {
        return content;
    }

    //显示行数
    public int getLineCount(int height, int lineNum) {
        return (int) (height * 1.0f / tvContent.getLineHeight() + lineNum);
    }

    //建立读书控制器
    public void setReadBookControl(ReadBookControl readBookControl) {
        setTextKind(readBookControl);
        setBg(readBookControl);
    }

    //建立阅读界面背景
    public void setBg(ReadBookControl readBookControl) {
        if (readBookControl.getTextDrawableIndex() != -1 || readBookControl.getIsNightTheme()) {
            ivBg.setImageResource(readBookControl.getTextBackground());
            tvTitle.setTextColor(readBookControl.getTextColor());
            tvContent.setTextColor(readBookControl.getTextColor());
            tvPage.setTextColor(readBookControl.getTextColor());
            vBottom.setBackgroundColor(readBookControl.getTextColor());
            tvLoading.setTextColor(readBookControl.getTextColor());
            tvErrorInfo.setTextColor(readBookControl.getTextColor());
        } else {
            /*ACache aCache = ACache.get(this.getContext());
            ivBg.setImageBitmap(aCache.getAsBitmap("customBg"));
            tvTitle.setTextColor(readBookControl.getTextColorCustom());
            tvContent.setTextColor(readBookControl.getTextColorCustom());
            tvPage.setTextColor(readBookControl.getTextColorCustom());
            vBottom.setBackgroundColor(readBookControl.getTextColorCustom());
            tvLoading.setTextColor(readBookControl.getTextColorCustom());
            tvErrorInfo.setTextColor(readBookControl.getTextColorCustom());*/
        }
    }

    //建立阅读字体大小,上下间距
    public void setTextKind(ReadBookControl readBookControl) {
        tvContent.setTextSize(readBookControl.getTextSize());
        tvContent.setLineSpacing(readBookControl.getTextExtra(), readBookControl.getLineMultiplier());
    }
}
